package controller;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;

import common.SignContinuity;
import pojo.Sign;
import pojo.User;
import service.SignServiceI;
import service.UserServiceI;

@Controller
@RequestMapping("sign")
public class SignController {

	@Autowired
	private SignServiceI signServiceI;
	@Autowired
	private UserServiceI userServiceI;
	@RequestMapping("sign")
	@ResponseBody
	@Transactional(rollbackFor=Exception.class)
	    /**
	    　　* @param [request, session]
	    　　* @return java.lang.String
	    　　* @author：千夜
	    　　* @date 2019/4/20 22:25
	     　 * @description: 实现签到
	    　　*/
	public String sign(HttpServletRequest request,HttpSession session) throws ParseException {
		User user=(User) session.getAttribute("user");
		if(user==null) {//未登录
			Map<String,Object> map = new HashMap<String,Object>();
    		map.put("result", "unlogin");
		    Gson gson=new Gson();
            String result = gson.toJson(map);
    		return result;
		}else {//已登录
			Integer userId=user.getUserId();
			Sign sign=signServiceI.SignRecord(userId);//查询是否有签到记录
			if(sign==null) {//没有签到记录
				Sign sign2=new Sign();
				sign2.setUserId(userId);
				/***********************获取系统时间*************************************/
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			    Calendar c = Calendar.getInstance();
		        c.setTime(new Date());
		        c.add(Calendar.DATE, - 7);
		        Date d = c.getTime();
		        String signDate = format.format(d);
		        System.out.print(signDate+"--1");
		        /**********************************************************/
				sign2.setSignDate(signDate);
				int signContinuity=1;
				sign2.setSignContinuity(signContinuity);
				try {
					signServiceI.signFirst(sign2);
					Map<String,Object> map = new HashMap<String,Object>();
	        		map.put("gain", 0);
	        		map.put("days", 1);
	        		map.put("result", "success");
	        		Gson gson=new Gson();
		            String result = gson.toJson(map);
		        	return result;
				} catch (Exception e) {
					e.printStackTrace();
				}
			}else {//有签到记录，不是第一次签到
				Integer signId=sign.getSignId();
				String lastSignDate=sign.getSignDate();//获取上一次签到时间
				/***********************获取系统时间*************************************/
				SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置时间格式
				String signDate = df.format(new Date());
		        /**********************************************************/
		        if(lastSignDate.equals(signDate)) {//时间相同，表示今天已经签到过了
	        		Map<String,Object> map = new HashMap<String,Object>();
	        		map.put("result", "alreadySign");
        		    Gson gson=new Gson();
	                String result = gson.toJson(map);
	        		return result;
		        }else {//时间不同，判断是否连续签到
		        	DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
		        	long days=dateFormat.parse(signDate).getTime()-dateFormat.parse(lastSignDate).getTime();
		        	days= days / (1000 * 60 * 60 * 24) ;//相差天数
		        	int day=(int)days;
		        	System.out.print(day);
		        	if(day>1) {//签到间隔大于一天，不是连续签到
		        		Sign sign2=new Sign();
		        		sign2.setSignId(sign.getSignId());
		        		sign2.setSignDate(signDate);
		        		int signContinuity=1;
		        		sign2.setSignContinuity(signContinuity);//将连续签到天数归1
		        		try {
							signServiceI.UpdateSign(sign2);
							Map<String,Object> map = new HashMap<String,Object>();
							map.put("gain", 0);
							map.put("days", 1);
							map.put("result", "success");
							Gson gson=new Gson();
							String result = gson.toJson(map);
							return result;
						} catch (Exception e) {
							e.printStackTrace();
							Map<String,Object> map = new HashMap<String,Object>();
			        		map.put("result", "false");
			        		Gson gson=new Gson();
				            String result = gson.toJson(map);
				            return result;
						}
		        	}else {//连续签到/判断连续签到天数
		        		int signContinuity=sign.getSignContinuity();
		        		SignContinuity sContinuity=new SignContinuity();
		        		int integration=sContinuity.signDay(signContinuity);//返回联系签到获得的积分
		        		System.out.println(integration);
		        		int lastintegration=user.getIntegration();
		        		User user2=new User();
		        		user2.setUserId(userId);
		        		user2.setIntegration(integration+lastintegration);//更新用户积分
		        		Sign sign2=new Sign();
		        		sign2.setSignId(signId);
		        		sign2.setSignContinuity(signContinuity+1);
		        		sign2.setSignDate(signDate);
		        		try {
		        			userServiceI.CompleteUserInformation(user2);
		        			signServiceI.UpdateSign(sign2);
						} catch (Exception e) {
							e.printStackTrace();
							Map<String,Object> map = new HashMap<String,Object>();
			        		map.put("result", "false");
			        		Gson gson=new Gson();
				            String result = gson.toJson(map);
				        	return result;
						}
		        		String gain=String.valueOf(integration);
		        		Map<String,Object> map = new HashMap<String,Object>();
		        		map.put("result", "success");
		        		map.put("gain", gain);
		        		map.put("days", signContinuity+1);
	        		    Gson gson=new Gson();
		                String result = gson.toJson(map);
		        		return result;
		        	}
		        }
			}
		}
		return null;
		
	}
}
